<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { compile } from 'path-to-regexp'

const levelList = ref([] as any)
const router = useRouter()
const routerValue: any = computed(() => router.currentRoute.value)

const isDashboard = (route: any) => {
  const name = route && route.name
  if (!name) {
    return false
  }
  return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
}
const getBreadcrumb = () => {
  // 如果 routerValue.value.matched 有值，取出有 meta 与 meta.title 的项
  // meta.title 与 'Dashboard' 是否一致

  if (routerValue.value.matched != null) {
    let matched = routerValue.value.matched.filter(
      (item: any) => item.meta && item.meta.title
    )
    const first = matched[0]

    // 一致的话
    if (isDashboard(first)) {
      matched = [{ path: '/dashboard', meta: { title: 'Dashboard' } }].concat(
        matched
      )
    }

    // 不一致的话，直接赋值
    levelList.value = matched.filter(
      (item: any) =>
        item.meta && item.meta.title && item.meta.breadcrumb !== false
    )
  }
}
getBreadcrumb()

const pathCompile = (path: any) => {
  // var toPath = pathToRegexp.compile(path)
  var toPath = compile(path)
  return toPath(routerValue.params)
}
const handleLink = (item: any) => {
  if (item.redirect) {
    router.push(item.redirect)
    return
  }
  router.push(pathCompile(item.path))
}

watch(routerValue, () => {
  getBreadcrumb()
})
</script>

<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <!-- 没有重定向或最后一个给普通标签 -->
        <span
          v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
          class="no-redirect"
          >{{ item.meta.title }}</span
        >
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
